package com.my.lock.v21;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by ZhongGang
 * at 2018/7/30 18:19
 */
public class ConcurrentQueue {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentQueue.class);

    public static void main(String[] args) throws Exception {
        Queue<Integer> queue = new ConcurrentLinkedQueue<>();
        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            int finalI = i;
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    queue.offer(finalI);
                }
            });
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        LOGGER.info("queue: {}", queue);

        for (int i = 0; i < 20; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Integer dequeue = queue.poll();
                    LOGGER.info("dequeue: {}, queue: {}", dequeue, queue);
                }
            });
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        LOGGER.info("queue: {}", queue);
    }
}
